package mya.mes.mdc.logic.dispatch.executor;

import mya.common.jpa.JPAUtils;
import mya.common.jpa.context.NoLoginLogic;
import mya.common.jpa.context.ServiceContext;
import mya.mes.mdc.model.dispatch.MdcDispatchContent;
import mya.mes.mdc.weixin.WxUploadManager;

/**
 * 定期发送报警消息<br>
 * 通过定期的方式，而不是实时的方式，确保发送之间有一定的时间间隔，确保消息发送成功???
 */
public class DispatchTimerTask implements Runnable {
    private volatile MdcDispatchContent dispatchContent = null;
    @Override
    public void run() {
        try {
            if (dispatchContent == null) {
                dispatchContent = DispatchExecutor.getInstance().getDispatchCurrent().getDispatch();
            }
            if (dispatchContent == null) {
                System.out.println("dispatchContent == null");
                DispatchExecutor.getInstance().getDispatchCurrent().updateCache();
                return;
            }
            WxUploadManager.getInstance().publish(dispatchContent.getJsonStr());
            delete(dispatchContent.getObjectId());
        } catch (Throwable ex) {
            System.out.println("===================MQTT远程发送失败：" + (dispatchContent == null ? "" : dispatchContent.getObjectId()));
            ex.printStackTrace();
            return;
        }

        System.out.println("MQTT远程发送成功：" + (dispatchContent == null ? "" : dispatchContent.getObjectId()));
        //消息发送成功,设置为NULL，下一个周期取下一条发送
        //如果没有设置为NULL，下一个定时器周期，继续发送当前记录
        dispatchContent = null;
    }


    public MdcDispatchContent delete(Long contentId) throws Exception {

        NoLoginLogic logic = new NoLoginLogic(JPAUtils.DEFAULT_TENANT_ID) {
            @Override
            protected Object process(ServiceContext context) throws Exception {

                MdcDispatchContent content = context.em.find(MdcDispatchContent.class, contentId);

                if (content == null) {
                    return null;
                }

                context.em.remove(content);


                return content;
            }
        };

        return (MdcDispatchContent) logic.callLogic();
    }
}
